<template>
    <div class="app-container">
      <!-- 输入表单 -->
      <el-form label-width="120px">
        <el-form-item label="商品名">
          <el-input v-model="goods.name" />
        </el-form-item>
        
        <el-form-item label="商品价格">
            <el-input v-model="goods.price" />
        </el-form-item>
        <el-form-item label="商品库存">
          <el-input-number v-model="goods.stock" :min="0"/>
        </el-form-item>
        <el-form-item label="商品图片">
            <el-upload
            :action="BASE_API + '/goods/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            class="avatar-uploader">
            <img v-if="goods.picture" :src="goods.picture" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>
  
        <el-form-item>
          <el-button type="primary" @click="saveOrUpdate()">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  
  <script>
import goodsApi from "@/api/goods/goods";
  export default {
      data() {
          return {
                BASE_API: 'http://localhost:8888',
              goods:{
                stock: 0,
                price: 0
              }
          }
      },
      created() {
        if(this.$route.params.id){
          const id = this.$route.params.id;
          this.fetchDataById(id)
        }
      },
      methods: {
        fetchDataById(id){
          goodsApi.getGoodsById(id)
          .then(response => {
            this.goods = response.data
          })
        },
        //添加
        save(){
          goodsApi.saveGoods(this.goods)
          .then((response) => {
              this.$message({
                  type: 'success',
                  message: '添加成功!'
              });
              //跳转列表页面
              this.$router.push({path:'/goods/list'})
          })
        },
        //修改
        update(){
          goodsApi.updateGoods(this.goods)
          .then((response) => {
              this.$message({
                  type: 'success',
                  message: '修改成功!'
              });
              //跳转列表页面
              this.$router.push({path:'/goods/list'})
          })
        },
        saveOrUpdate(){
          if(this.goods.id){
            this.update()
          }else{
            this.save()
          }
        },
        // 上传成功回调
      handleAvatarSuccess(res, file) {
        // console.log(res)
        if (res.code==20000) {
          // console.log(res)
          this.goods.picture = res.data
          // 强制重新渲染
          this.$forceUpdate()
        } else {
          this.$message.error('上传失败 （非0）')
        }
      },

      // 错误处理
      handleAvatarError() {
        console.log('error')
        this.$message.error('上传失败（http失败）')
      },

      // 上传校验
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      }
      },
      
  }
  </script>

  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>